<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="auto">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="部门名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="部门状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="全部" clearable style="width: 100px">
            <el-option :value="1" label="正常" />
            <el-option :value="0" label="禁用" />
          </el-select>
        </el-form-item>

        <el-form-item class="search-buttons">
          <el-button class="filter-item" type="primary" icon="search" @click="handleQuery">
            搜索
          </el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="hover" class="data-table">
      <div class="data-table__toolbar">
        <div class="data-table__toolbar--actions">
          <el-button
            v-hasPerm="['sys:dept:add', 'system:depart:add']"
            type="success"
            icon="plus"
            @click="handleOpenDialog()"
          >
            新增
          </el-button>
          <el-button
            v-hasPerm="['sys:dept:delete', 'system:depart:delete']"
            type="danger"
            :disabled="selectIds.length === 0"
            icon="delete"
            @click="handleDelete()"
          >
            删除
          </el-button>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="deptList"
        row-key="id"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        class="data-table__content"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="name" label="部门名称" min-width="200" />
        <el-table-column prop="code" label="部门编号" width="200" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 1" type="success">正常</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="sort" label="排序" width="100" />

        <el-table-column label="操作" fixed="right" align="left" width="200">
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:dept:add', 'system:depart:add']"
              type="primary"
              link
              size="small"
              icon="plus"
              @click.stop="handleOpenDialog(scope.row.id, undefined)"
            >
              新增
            </el-button>
            <el-button
              v-hasPerm="['sys:dept:edit', 'system:depart:edit']"
              type="primary"
              link
              size="small"
              icon="edit"
              @click.stop="handleOpenDialog(scope.row.parentId, scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              v-hasPerm="['sys:dept:delete', 'system:depart:delete']"
              type="danger"
              link
              size="small"
              icon="delete"
              @click.stop="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      @closed="handleCloseDialog"
    >
      <el-form ref="deptFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="上级部门" prop="parentId">
          <el-tree-select
            v-model="formData.parentId"
            placeholder="选择上级部门"
            :data="deptOptions"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item label="部门名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入部门名称" />
        </el-form-item>

        <!-- 0 平台 1 监管区 2 过货商 3 供箱单位 4 担保商 5 供应商 6 贸易商 7 蒙方承运单位 8 中方承运单位 14 公司 -->
        <el-form-item v-if="showDept" label="部门类型" prop="deptType">
          <el-select v-model="formData.deptType">
            <el-option :key="0" label="场站平台" :value="0" />
            <el-option :key="1" label="监管区" :value="1" />
            <el-option :key="2" label="过货商" :value="2" />
            <el-option :key="3" label="供箱单位" :value="3" />
            <el-option :key="4" label="担保商" :value="4" />
            <el-option :key="5" label="供应商" :value="5" />
            <el-option :key="6" label="贸易商" :value="6" />
            <el-option :key="7" label="蒙方承运单位" :value="7" />
            <el-option :key="8" label="中方承运单位" :value="8" />
            <el-option :key="14" label="公司" :value="14" />
          </el-select>
        </el-form-item>

        <!-- 过货商类型：0 单一过货商 1 过贸一体 -->
        <el-form-item v-if="showTrader" label="机构类型" prop="gmType">
          <el-select v-model="formData.gmType">
            <el-option :key="0" label="单一过货商" :value="0" />
            <el-option :key="1" label="过贸一体" :value="1" />
          </el-select>
        </el-form-item>

        <!-- 监管区类型：0 本场站 1 其他场站 -->
        <el-form-item v-if="showSuper" label="监管类型" prop="jgType">
          <el-select v-model="formData.jgType">
            <el-option :key="0" label="本场站" :value="0" />
            <el-option :key="1" label="其他场站" :value="1" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="showSuperDept" label="监管部门" prop="jgqIds">
          <el-select v-model="formData.jgqIds" multiple placeholder="请选择监管区">
            <el-option
              v-for="item in superDeptOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="showIdCard" label="信用代码" prop="idCard">
          <el-input
            v-model="formData.idCard"
            placeholder="请输入社会信用代码"
            class="input-with-append"
          >
            <template #append>
              <el-button
                type="primary"
                style="background-color: #4080ff; color: white"
                @click="openLink"
              >
                天眼查
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item v-if="showMgName" label="蒙古名称" prop="mgName">
          <el-input v-model="formData.mgName" placeholder="请输入蒙古名称" />
        </el-form-item>

        <el-form-item v-if="showDept" label="联系人" prop="linkMan">
          <el-input v-model="formData.linkMan" placeholder="请输入联系人" />
        </el-form-item>

        <el-form-item v-if="showDept" label="联系电话" prop="linkPhone">
          <el-input v-model="formData.linkPhone" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item v-if="showDept" label="联系账号" prop="linkAccount">
          <el-input v-model="formData.linkAccount" placeholder="请输入联系人账号" />
        </el-form-item>

        <el-form-item v-if="showDept" label="通信地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入通信地址" />
        </el-form-item>

        <el-form-item label="显示排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            controls-position="right"
            style="width: 100px"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="部门状态">
          <el-radio-group v-model="formData.status">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import UserAPI, { UserProfileVO } from "@/api/system/user.api";
import DeptAPI, { DeptForm, DeptQuery, DeptVO } from "@/api/system/dept.api";

defineOptions({
  name: "Dept",
  inheritAttrs: false,
});

const queryFormRef = ref();
const deptFormRef = ref();
const showDept = ref(false);
const showTrader = ref(false);
const showMgName = ref(false);
const showSuper = ref(false);
const showSuperDept = ref(false);
const showIdCard = ref(false);
const loading = ref(false);
const selectIds = ref<number[]>([]);
const queryParams = reactive<DeptQuery>({});
const userProfile = ref<UserProfileVO>({});

const dialog = reactive({
  title: "",
  visible: false,
});

const deptList = ref<DeptVO[]>();
const deptOptions = ref<OptionType[]>();
const superDeptOptions = ref<OptionType[]>();
const formData = reactive<DeptForm>({
  status: 1,
  parentId: "0",
  sort: 1,
});

const rules = reactive({
  parentId: [{ required: true, message: "上级部门不能为空", trigger: "change" }],
  name: [{ required: true, message: "部门名称不能为空", trigger: "blur" }],
  deptType: [{ required: true, message: "部门类型不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
});

// 用户信息
const loadUserProfile = async () => {
  try {
    const data = await UserAPI.getProfile();
    userProfile.value = data;
    if (userProfile.value.tenantId === "1") {
      showDept.value = true;
    } else {
      showDept.value = false;
    }
  } catch (error) {
    console.error("获取用户租户信息失败", error);
  }
};

// 监听 formData.deptType 的变化
watch(
  () => formData.deptType,
  async (newVal) => {
    if (showDept) {
      if (newVal === undefined) {
        console.error("deptType is undefined");
        return;
      }

      showTrader.value = newVal === 2;
      showSuper.value = newVal === 1;
      showSuperDept.value = newVal === 2;
      showIdCard.value = newVal === 5;
      showMgName.value = [1, 2, 5, 7].includes(newVal);

      if (newVal === 2) {
        await updateSuperDeptOptions(1);
      }
    }
  }
);

// 查询部门
function handleQuery() {
  loading.value = true;
  DeptAPI.getList(queryParams).then((data) => {
    deptList.value = data;
    loading.value = false;
  });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

// 处理选中项变化
function handleSelectionChange(selection: any) {
  selectIds.value = selection.map((item: any) => item.id);
}

// 根据部门类型更新部门选项
async function updateSuperDeptOptions(deptType: number) {
  try {
    if (deptType !== null && deptType !== undefined) {
      const deptData = await DeptAPI.getUserDept(deptType);
      superDeptOptions.value = deptData;
    } else {
      superDeptOptions.value = [];
    }
  } catch (error) {
    console.error("获取部门数据失败", error);
  }
}

/**
 * 打开部门弹窗
 *
 * @param parentId 父部门ID
 * @param deptId 部门ID
 */
async function handleOpenDialog(parentId?: string, deptId?: string) {
  // 加载部门下拉数据
  const data = await DeptAPI.getOptions();
  deptOptions.value = [
    {
      value: "0",
      label: "顶级部门",
      children: data,
    },
  ];
  // 设置表单默认值
  dialog.visible = true;
  if (deptId) {
    dialog.title = "修改部门";
    DeptAPI.getFormData(deptId).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增部门";
    resetForm()
    formData.parentId = parentId || "0";
  }
}

// 提交部门表单
function handleSubmit() {
  deptFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const deptId = formData.id;
      if (deptId) {
        DeptAPI.update(deptId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        DeptAPI.create(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 删除部门
function handleDelete(deptId?: number) {
  const deptIds = [deptId || selectIds.value].join(",");

  if (!deptIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      DeptAPI.deleteByIds(deptIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 重置表单
function resetForm() {
  deptFormRef.value.resetFields();
  deptFormRef.value.clearValidate();

  formData.id = undefined;
  formData.parentId = "0";
  formData.status = 1;
  formData.sort = 1;
  formData.deptType = undefined;
  showTrader.value = false;
  showMgName.value = false;
  showSuper.value = false;
  showSuperDept.value = false;
  showIdCard.value = false;
  formData.mgName = undefined;
  formData.jgqIds = undefined;
  formData.gmType = undefined;
  formData.jgType = undefined;
  formData.idCard = undefined;
  formData.linkMan = undefined;
  formData.linkPhone = undefined;
  formData.linkAccount = undefined;
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}

// 打开链接
const openLink = () => {
  const idCard = formData.idCard;
  let url = "https://www.tianyancha.com/nsearch";
  // 如果 idCard 有值，则拼接查询参数
  if (idCard) {
    url += `?key=${encodeURIComponent(idCard)}`;
  }
  window.open(url, "_blank");
};

onMounted(() => {
  handleQuery();
  loadUserProfile();
});
</script>
